package com.lz.ub.hm.impl

import android.os.Handler
import android.os.Looper
import android.os.Message
import com.lz.ub.hm.SUCCESS
import com.lz.ub.hm.UBCommandCallback
import com.lz.ub.hm.UBHandler
import com.lz.ub.hm.UBScanResult
import java.lang.ref.WeakReference

/**
 * @author you
 * 通用回调事件处理类
 */
class UBCommHandler(callback: UBCommandCallback) : Handler(Looper.getMainLooper()), UBHandler {

    companion object {
        //连接状态
        private const val MSG_CONNECTED_STATE = 1

        //发现写入特征
        private const val MSG_PROPERTY_STATE = 2

        //正式连接
        private const val MSG_SERVICE_STATE = 3

        //写数据回调
        private const val MSG_WRITE_DATA = 4

        //读取数据
        private const val MSG_READ_DATA = 5

        //扫描设备
        private const val MSG_SCAN = 6

        //异常
        private const val MSG_ERROR = 7
    }

    private val reference = WeakReference(callback)

    override val callback: UBCommandCallback?
        get() = reference.get()

    override fun handleMessage(msg: Message) {
        when (msg.what) {
            MSG_CONNECTED_STATE -> reference.get()?.onConnectedStateChanged(msg.arg2 == SUCCESS, msg.arg1)
            MSG_PROPERTY_STATE -> reference.get()?.onPropertyStateChanged(msg.arg1)
            MSG_SERVICE_STATE -> reference.get()?.onServiceStateChanged(msg.arg1, msg.arg2)
            MSG_WRITE_DATA -> reference.get()?.onWrite(msg.arg1)
            MSG_READ_DATA -> reference.get()?.onRead(msg.arg1, msg.obj as ByteArray, msg.arg2 shr(8) and(0xFF), msg.arg2 and(0xFF))
            MSG_SCAN -> reference.get()?.onScanResult(msg.obj as List<UBScanResult>)
            MSG_ERROR -> reference.get()?.onError(msg.obj as String)
        }
    }

    override fun sendConnectedStateChanged(isConn: Int, status: Int) {
        sendMessage(obtainMessage(MSG_CONNECTED_STATE, status, isConn))
    }

    override fun sendServiceStateChanged(status: Int, link: Int) {
        sendMessage(obtainMessage(MSG_SERVICE_STATE, status, link))
    }

    override fun sendPropertyStateChanged(status: Int) {
        sendMessage(obtainMessage(MSG_PROPERTY_STATE, status, 0))
    }

    override fun sendWrite(status: Int) {
        sendMessage(obtainMessage(MSG_WRITE_DATA, status, 0))
    }

    override fun sendRead(link: Int, bytes: ByteArray, startSize: Int) {
        sendMessage(obtainMessage(MSG_READ_DATA, link, startSize, bytes))
    }

    override fun sendScanResult(result: List<UBScanResult>) {
        sendMessage(obtainMessage(MSG_SCAN, result))
    }

    override fun sendError(err: String) {
        sendMessage(obtainMessage(MSG_ERROR, err))
    }
}